<?php
/**
 * 商城相关接口
 * */

namespace App\Http\Controllers;

use App\Http\Model\Hint;
use App\Http\Model\OutJson;
use App\Http\Services\FinanceServices;
use App\Http\Services\MallServices;
use App\Http\Services\MsgServices;
use App\Lib\signature;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Http\Services\GoodsLevelServices;
use App\Lib\Response;

class MallController extends BaseController
{
    protected $request;
    protected $service;
    private $service_msg;
    private $service_finance;

    public function __construct(Request $request, MallServices $mallServices, MsgServices $msgServices, FinanceServices $financeServices)
    {
        $this->request = $request;
        $this->service = $mallServices;
        $this->service_msg = $msgServices;
        $this->service_finance = $financeServices;
    }

    /**
     * @desc 商城商品列表
     * @param int $page
     * @param int $page_size
     * @param int $goods_type
     * @date 2019/1/8
     * */
    public function goods_list()
    {
            $page = !empty((int)$this->request->get('page_index')) && $this->request->get('page_index') >= 0 ? (int)$this->request->get('page_index') : 0;
            $page_size = !empty((int)$this->request->get('page_size')) && $this->request->get('page_size') > 0 ? (int)$this->request->get('page_size') : 10;
            $goods_type = (int)$this->request->get('goods_type');
            $mall_goods_class = (int) $this->request->get('mall_goods_class', 0);

            if (strlen($goods_type) < 0) {
                OutJson::outJsonResult(Hint::PARAM_ERROR, []);
            }
            $this->service->checkToken();
            $goods_list = $this->service->getGoodsList($goods_type, $page, $page_size, 0, $mall_goods_class);
            if(!empty($goods_list)){
                OutJson::outJsonResult(Hint::SUCCESS, $goods_list);
            }else{
                OutJson::outJsonNoData(Hint::SUCCESS);
            }

    }
    /**
     * @desc 商城商品列表
     * @param int $page
     * @param int $page_size
     * @param int $goods_type
     * @date 2019/1/8
     * */
    public function goods_list_v1()
    {
        $page = !empty((int)$this->request->get('page_index')) && $this->request->get('page_index') >= 0 ? (int)$this->request->get('page_index') : 0;
        $page_size = !empty((int)$this->request->get('page_size')) && $this->request->get('page_size') > 0 ? (int)$this->request->get('page_size') : 10;
        $goods_type = (int)$this->request->get('goods_type');
        $mall_goods_class = (int) $this->request->get('mall_goods_class', 0);

        if (strlen($goods_type) < 0) {
            OutJson::outJsonResult(Hint::PARAM_ERROR, []);
        }
        $this->service->checkToken();
        $goods_list = $this->service->getGoodsListV1($goods_type, $page, $page_size, $mall_goods_class);
        if(!empty($goods_list)){
            OutJson::outJsonResult(Hint::SUCCESS, $goods_list);
        }else{
            OutJson::outJsonNoData(Hint::SUCCESS);
        }

    }

    /**
     * @desc 商城商品购买or赠送
     * @param int $act_type 1:购买 2：赠送
     * @param int $to_user_id &2
     * @param string $sign
     * @param string $timestamp
     * */
    public function goods_shopping()
    {
        $act_type = $this->request->post('act_type');
        $to_user_id = $this->request->post('to_user_id');
        $goods_id = $this->request->post('goods_id');
        $sku_id = $this->request->post('sku_id');
        //$sign = $this->request->post('sign');
        //$timestamp = $this->request->post('timestamp');

        if(!(int)$act_type || !in_array($act_type,[1,2,3]) || !(int)$goods_id || /*!$sign || !$timestamp ||*/ !(int)$sku_id){
            OutJson::outJsonResult(Hint::PARAM_ERROR, []);
        }
        if (($act_type == 2) && (!(int)$to_user_id) ){
            OutJson::outJsonResult(Hint::PARAM_ERROR, []);
        }
        /*
        $data = $this->request->post();
        if(!signature::checkSign($data)){
            OutJson::outJsonResult(Hint::SIGN_ERROR, []);
        }
        */
        $this->service->checkToken();
        if ($to_user_id == null){
            $to_user_id = 0;
        }
        $cur_user_id = null;
        $ret = $this->service->shoppingService($act_type, $goods_id, $sku_id, $to_user_id, $cur_user_id, $give_good_id);
        if($ret === false){
            OutJson::outJsonNoData(Hint::ERROR);
        }elseif($ret === Hint::WAIT_OPEN){
            OutJson::outJsonNoData(Hint::WAIT_OPEN);
        }elseif($ret === 4001){
            OutJson::outJsonNoData(Hint::DIAMOND_NOT_ENOUGH);
        }elseif($ret === 7004){
            OutJson::outJsonNoData(Hint::CP_NOT_EXIST);
        }else{
            if ($act_type == 2 && !empty($cur_user_id)){
                $this->service_msg->give_mall($cur_user_id, $to_user_id, $goods_id);
            }

            if ($act_type == 3 && !empty($cur_user_id) && $give_good_id){
                $this->service_msg->give_mall($cur_user_id, $to_user_id, $give_good_id);
            }

            $rank_data = $this->service_finance->check_wealth_rank($cur_user_id);
            if (!empty($rank_data)){
                $this->service_msg->rank_update($cur_user_id, $rank_data['rank_name'],"", $rank_data['wealth_balance']);
            }
            OutJson::outJsonResult(Hint::SUCCESS, $ret);
        }
    }

    /**
     * 获取预加载资源列表
     */
    public function get_animate_resources(){
        $data = $this->service->get_animate_resources();
        Response::returnResult(Hint::SUCCESS, $data);
    }

    public function back_send_goods(Request $request){
        $validator = Validator::make($request->all(),[
            'user_id' => 'bail|required|integer|exists:user',
            'to_user_id' => 'bail|required|string',
            'goods_id' => 'bail|required|integer|exists:mall_goods',
            //'goods_name' => 'bail|required|string',
            //'goods_type' => ['bail','required','integer', Rule::in(1,2,3,4,5,6)],
            'sku_id' => 'bail|required|integer',
            'time_limit' => 'bail|required|numeric',
            'price' => 'bail|required|numeric',
            'act_type' => ['bail','required','integer',Rule::in(0,1)]
        ],[
            'user_id.required' => '用户ID必须',
            'user_id.exists' => '用户不存在',
            'to_user_id.required' => '被赠送人必须',
//            'to_user_id.exists' => '被赠送人不存在',
            'goods_id.required' => '赠送商品必须',
            'goods_id.exists' => '赠送商品不存在',
            'goods_name.required' => '赠送商品名必须',
            'goods_type.required' => '商品类型必须',
            'sku_id.required' => '商品SKU必须',
            'sku_id.exists' => '商品SKU必须',
            'time_limit.required' => '使用期限必须',
            'price.required' => '价格必须'
        ]);

        if($validator->fails()){
            Log::debug($validator->errors()->first());
            return OutJson::outJsonNoData(Hint::PARAM_ERROR);
        }
        if(empty($this->service->back_send_goods($request))){
            return OutJson::outJsonNoData(Hint::ERROR);
        }
        return OutJson::outJsonNoData(Hint::SUCCESS);
    }

    /**
     * 装扮作废
     */
    public function onVoidUserGoods(Request $request)
    {
        $params = $request->all();
        $validator = Validator::make($params, [
            'user_id' => 'bail|required|integer|exists:user',
            'goods_id' => 'required',
        ],[
            'user_id.required' => '用户ID必须',
            'user_id.integer' => '用户ID必须是数字',
            'user_id.exists' => '用户不存在',
            'goods_id.required' => '赠送商品必须',
        ]);

        if($validator->fails()){
            Log::debug($validator->errors()->first());
            return OutJson::outJsonNoData(Hint::PARAM_ERROR);
        }

        if(empty($this->service->onVoidUserGoods($params['user_id'], $params['goods_id']))){
            return OutJson::outJsonNoData(Hint::ERROR);
        }
        return OutJson::outJsonNoData(Hint::SUCCESS);
    }

    /**
     * 活动返现 赠送用户商品
     * */
    public function giveUserGoods(Request $request){
        $params = $request->post();
        $ret = $this->service->giveUserGoods($params);

        write_log('giveUserGoods','活动返现（赠送用户商品）',$ret);

        OutJson::outJsonResult($ret['code'], $ret['data']);
    }

    ################# 后台调用 ##########################################

    /**
     * 商品创建
     * */
    public function goodsCreate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'goodsCreate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 商品标签创建
     */
    public function labelCreate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'labelCreate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 商品标签编辑
     */
    public function labelEdit()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'labelEdit', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 删除商品标签
     */
    public function labelDel()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'labelDel', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 商品更新
     * */
    public function goodsUpdate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'goodsUpdate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 商品删除
     * */
    public function goodsRemove()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'goodsRemove', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 商品规格创建
     * */
    public function goodsSkuCreate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'goodsSkuCreate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 商品规格更新
     * */
    public function goodsSkuUpdate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'goodsSkuUpdate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 商品规格删除
     * */
    public function goodsSkuRemove()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'goodsSkuRemove', $this->requestData);

        } while (false);

        $this->responseData();
    }

    public function createMallUnionGoods(Request $request) {
        $validator = Validator::make($request->all(),[
            'union_id' => 'bail|required|integer|exists:union,id',
            'good_id' => ['bail', 'required','integer', Rule::exists('mall_goods', 'goods_id')->where(function($query) {
                $query->where('extra_type', 1);
            })],
            'status' => ['bail','required','integer', Rule::in(0, 1)],
        ],[
            'union_id.required' => '公会不可为空',
            'union_id.exists' => '公会不存在',
            'good_id.required' => '商品可为空',
            'good_id.exists' => '商品不存在',
        ]);
        if($validator->fails()){
            OutJson::outJsonCustom(Hint::PARAM_ERROR, $validator->errors()->first());
        }
        $ret = $this->service->createMallUnionGoods($request->only(['union_id', 'good_id', 'status']));
        if(Hint::PARAM_ERROR === $ret) OutJson::outJsonCustom(Hint::PARAM_ERROR, '已存在,不可重复添加');
        OutJson::outJsonNoData(Hint::SUCCESS);
    }

    public function updateMallUnionGoods(Request $request) {
        $validator = Validator::make($request->all(),[
            'id' => 'bail|required|integer|exists:mall_union_goods,m_u_g_id',
            'union_id' => 'bail|required|integer|exists:union,id',
            'good_id' => 'bail|required|integer|exists:mall_goods,goods_id',
            'status' => ['bail','required','integer', Rule::in(0, 1)],
        ],[
            'id.required' => '公会商品id不可为空',
            'id.exists' => '公会商品不存在',
            'union_id.required' => '公会不可为空',
            'union_id.exists' => '公会不存在',
            'good_id.required' => '商品可为空',
            'good_id.exists' => '商品不存在',
        ]);
        if($validator->fails()){
            OutJson::outJsonCustom(Hint::PARAM_ERROR, $validator->errors()->first());
        }
        $ret = $this->service->updateMallUnionGoods($request->post('id'), $request->only(['union_id', 'good_id', 'status']));
        if(Hint::PARAM_ERROR === $ret) OutJson::outJsonCustom(Hint::PARAM_ERROR, '已存在,不可重复添加');
        OutJson::outJsonNoData(Hint::SUCCESS);
    }

    /**
     * 商品等级
     */
    public function goodsLevelList()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }
            $service = new GoodsLevelServices();
            $where = [];
            $this->callCommon($service, 'getGoosLevelList', $where);

        } while (false);

        $this->responseData();
    }

    // 商城
    public function getMallNav()
    {
        $page = 0;
        $page_size = 1;
        $goods_type = (int)$this->request->get('goods_type');

        if (strlen($goods_type) < 0) {
            OutJson::outJsonResult(Hint::PARAM_ERROR, []);
        }
        $data = [];
        $nav = $this->service->getMallNav();
        $navList = $nav['code']==Hint::SUCCESS ? $nav['data'] : [];
        foreach ($navList as $value) {
            $mall_goods_class = $value['mall_goods_class'];
            //$goods_list = $this->service->getGoodsList($goods_type, $page, $page_size, 0, $mall_goods_class);
            $goods_list = $this->service->getGoodsListV1($goods_type, $page, $page_size, $mall_goods_class);
            if ($goods_list['list']){
                array_push($data, $value);
            }
        }

        if(!empty($data)){
            OutJson::outJsonResult(Hint::SUCCESS, $data);
        }else{
            OutJson::outJsonNoData(Hint::SUCCESS);
        }
    }
}
